<?php
namespace app\common\component\help_appointment;

use think\Session;
use app\common\component\user\UserModel;
use app\common\component\help_get\HelpGetModel;
use app\common\component\help_to\HelpToService;

class HelpAppointmentService {
	public function create($data) {
		$HelpAppointmentModel = new HelpAppointmentModel($data);

    	if($HelpAppointmentModel -> save()) {
    		return [
    			'code' => 0,
    			'message' => '预约成功!',
    			'data' => [
    				'help_appointment' => $HelpAppointmentModel
    			]
    		];
    	}

    	return [
			'code' => -1,
			'message' => '预约失败!'
		];
	}
	
	public function delete($help_appointment_id) {
    	if(HelpAppointmentModel::where('help_appointment_id', $help_appointment_id) -> delete()) {
    		return [
    			'code' => 0,
    			'message' => '删除预约成功!',
    		];
    	}

    	return [
			'code' => -1,
			'message' => '删除预约失败!'
		];
	}

	public function appointment($help_appointment_id, $money) {
		$post['help_appointment_id'] = $help_appointment_id;
    	$post['user_id'] = Session::get('user_id');
    	$post['appointment_money'] = $money;
    	$post['remaining_money'] = $money;
    	$post['create_time'] = $post['begin_time'] = time();
    	$post['to_num'] = 0;
    	$post['status'] = 0;

		return $this -> create($post);
	}

	public function getHelpAppointment($user_id = null) {
		if(!$user_id) {
			$user_id = Session::get('user_id');
		}

		$getHelpAppointment = HelpAppointmentModel::get(['user_id' => $user_id]);

		if($getHelpAppointment) {
			return [
				'code' => 0,
				'data' => [
					'help_appointment' => $getHelpAppointment
				]
			];
		}

		return [
			'code' => -1,
			'message' => '失败'
		];
	}

	public function getHelpAppointmentLastId() {
		$restulHelpAppointment = (new HelpAppointmentModel()) -> order('help_appointment_id DESC') -> find();
		if($restulHelpAppointment) {
			return [
				'code' => 0,
				'data' => [
					'help_appointment_id' => $restulHelpAppointment['help_appointment_id']
				]
			];
		}

		return [
			'code' => 0,
			'data' => [
				'help_appointment_id' => 0
			]
		];
	}

	public function clearTable() {
		$restultHelpAppointment = HelpAppointmentModel::order('help_appointment_id DESC') -> find();
		$today = strtotime(date('Ymd'));

		if($restultHelpAppointment && $restultHelpAppointment -> getData('create_time') < $today) {
			$restultHelpAppointments = HelpAppointmentModel::where('create_time <= ' . $today) -> order('help_appointment_id DESC') -> select();

			foreach($restultHelpAppointments as $restultHelpAppointment) {
				$dataHelpAppointment = $restultHelpAppointment -> toArray();
				unset($dataHelpAppointment['help_appointment_id']);
				$dataHelpAppointment['create_time'] = strtotime($dataHelpAppointment['create_time']);
				$dataHelpAppointment['status'] = 2;
				
				(new HelpAppointmentOldModel($dataHelpAppointment)) -> save();
			}

			return \think\Db::query('TRUNCATE table ' . (new HelpAppointmentModel()) -> getTable());
		}

		return false;
	}
	
	/*
	 * 匹配提现订单
	 */
	public static function matchHelpGetOrder() {
		$getHelpAppointments =  HelpAppointmentModel::where('status', 0) -> where('create_time', '>', strtotime(date('Ymd'))) -> order('to_num ASC, help_appointment_id ASC') -> select();

		$helpToService = new HelpToService();
		$currentTime = time();
		$helpToData = [
			'create_time' => $currentTime,
			'begin_time' => $currentTime,
			'status' => 1
		];

		foreach($getHelpAppointments as $getHelpAppointment) {
			$getHelpGet = HelpGetModel::where('status = 0 AND money <= :money AND user_id <> :user_id AND help_to_id = 0') -> bind(['money' => $getHelpAppointment -> remaining_money, 'user_id' => $getHelpAppointment -> user_id]) -> order('sort ASC, help_get_id ASC') -> find();

			if(!$getHelpGet) {
				continue;
			}

			$helpToData['help_get_id'] = $getHelpGet -> help_get_id;
			$helpToData['user_id'] = $getHelpAppointment -> user_id;
			$helpToData['money'] = $getHelpGet -> money;

			\think\Db::startTrans();
			try {
				$resultHelpTo = $helpToService -> create($helpToData);
				if($resultHelpTo['code'] !== 0) {
					throw new \Exception($resultHelpTo['message']);
				}

				$getHelpGet -> help_to_id = $resultHelpTo['data']['help_to'] -> help_to_id;
				$getHelpGet -> begin_time = $currentTime;
				$getHelpGet -> status = 1;
				if(!$getHelpGet -> save()) {
					throw new \Exception('帮助提现修改失败');
				}

				$getHelpAppointment -> remaining_money -= $getHelpGet -> money;
				$getHelpAppointment -> begin_time = $currentTime;
				$getHelpAppointment -> to_num += 1;
				// 判断剩余金钱是否为零
				if($getHelpAppointment -> remaining_money <= 0) {
					$getHelpAppointment -> status = 1;
				}

				if(!$getHelpAppointment -> save()) {
					throw new \Exception('预约打款修改失败');
				}

				$getUserHelpTo = UserModel::get(['user_id' => $resultHelpTo['data']['help_to'] -> getData('user_id')]);
				winicSMS($getUserHelpTo -> phone, ['name' => $getUserHelpTo -> realname], 20);

				$getUserHelpGet = UserModel::get(['user_id' => $getHelpGet -> getData('user_id')]);
				winicSMS($getUserHelpGet -> phone, ['name' => $getUserHelpGet -> realname], 10);

				\think\Db::commit();
			} catch(\Exception $e) {
				\think\Db::rollback();

				\think\Log::error($e -> getMessage());
			}
		}

		return true;
	}

	public function getAll($page = 10) {
		return (new HelpAppointmentModel()) -> alias('h_a')
    	-> join('league_user u', 'h_a.user_id = u.user_id')
    	-> field(
    		'h_a.help_appointment_id, h_a.appointment_money, h_a.remaining_money, h_a.create_time, h_a.begin_time, h_a.to_num, h_a.status, ' .
    		'u.username'
    	)
    	-> order('h_a.to_num ASC, h_a.help_appointment_id ASC') -> paginate($page);
	}
}
?>